<?php
// +----------------------------------------------------------------------
// | UCToo [ Universal Convergence Technology ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2021 https://www.uctoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Patrick <contact@uctoo.com>
// +----------------------------------------------------------------------

namespace app\controller;

use uctoo\middleware\Applet;
use uctoo\middleware\H5PaltAuth;
use uctoo\model\saas\EmployeeAccount;
use uctoo\util\library\H5PlatAuth as AuthInstance;
use uctoo\util\library\OfficialAccount;
use think\facade\Cache;
use uctoo\ThinkEasyWeChat\MiniProgram\CloudFunction\ServiceProvider;
use think\facade\Config;

class H5plat extends MiniProgram
{
    protected $middleware = [
        H5PaltAuth::class  => ['except' => ['login','bind','loginRedirect','doRedirect','sendTplMsg']],
        Applet::class => ['except' => ['login','bind','loginRedirect','doRedirect','sendTplMsg']]
    ];

    public function loginRedirect(){
        $redirect_url = $this->request->get('redirect_url/s');
        if(!$redirect_url){
            $this->error('参数错误');
        }
       OfficialAccount::instance()->oauth->setRedirectUrl($this->request->domain().'/h5plat/doRedirect?url='.$redirect_url)->redirect()->send();
    }

    public function doRedirect($url,$code = ''){
        return redirect(urldecode($url).'?code='.$code);
    }

    public function login(){
        $code = $this->request->get('code/s',false);
        if(!$code){
            $this->error('参数错误');
        }
        try{
            $user = OfficialAccount::instance()->oauth->user();
        }catch (AuthorizeFailedException $e){
            $this->error('请刷新后重试'.$e->getMessage());
        }
        $openid = $user->getId();
        $account = (new EmployeeAccount())->where(['openid'=>$openid])->field(['id','account_type','applet_appid'])->find();
        if(!$account){
            $token = 'account_bind_token_'.md5($openid);
            Cache::set($token,$user->getOriginal(),600);
            $this->success('请先绑定账号',['need_bind_account' => true,'token' => $token]);
        }
        $this->returnToken($account);
    }

    public function bind(){
        $username  = $this->request->post('account/s',false);
        $password  = $this->request->post('password/s',false);
        if(!$username || !$password){
            $this->error('请填写正确的账号密码');
        }
        $token = $this->request->post('token/s');
        if(!Cache::has($token)){
            $this->error('请刷新后重试');
        }
        $info = Cache::get($token);
        $account = (new EmployeeAccount())->where(['username'=>$username])->field(['id','password','account_type','applet_appid'])->find();
        if(!$account){
            $this->error('账号密码错误');
        }
        if($account['password'] !== EmployeeAccount::encryptPassword($password)){
            $this->error('账号密码错误');
        }
        $account->openid = $info['openid'];
        $account->save();
        $this->returnToken($account);
    }

    public function unBind(){
        EmployeeAccount::update(['openid'=>''],['id'=>$this->request->user['uid']]);
        $this->success('解除绑定成功');
    }


    /**
     * 获取员工信息
     */
    public function getAccountInfo(){
        $mapp = $this->request->mapp;
        $mapp->registerProviders([ServiceProvider::class]);
        $name = 'meiye';
        $postBody = [
            '$url' => 2 === $this->request->user['account_type'] ? 'shop' : 'staff',
            'data' => ['id'=> $this->request->user['uid']]
        ];
        $res = $mapp->cloud_function->invokeFunction($name,$postBody);
        $this->wxResult($res,false,function (&$data){
            $data = json_decode($data['resp_data']);
        });
    }

    /**
     * 发送模板消息
     */
    public function sendTplMsg(){
        $uid = $this->request->post('uid/s',false);
        $data = $this->request->post('data/a',false);
        if(!$uid || !$data){
            $this->error('参数错误');
        }
        // 获取用户id
        $openid = EmployeeAccount::where('id',$uid)->value('openid');
        if(!$openid){
            $this->error('参数错误');
        }
        $h5plat_config = Config::get('h5plat');
        $params = [
            "touser" => $openid,
            "template_id" => $h5plat_config['tpl_msg_id'],
            "url" => $h5plat_config['tpl_msg_turn_url'],
            "data" => $data
        ];
        OfficialAccount::instance()->template_message->send($params);
        $this->success('ok');
    }

    private function returnToken($account_info){
        $auth_data = [
            'uid' => $account_info['id'],
            'aid' => $account_info['applet_appid'],
            'account_type' => $account_info['account_type']
        ];
        $this->success('success',AuthInstance::instance()->TokenEncode($auth_data));
    }

}
